import {
  reportControllerAddMonth as addMonth,
  reportControllerCheckAddMonth as checkAddMonth,
} from '@/services/ess/diagnosisReport';
import { PlusOutlined } from '@ant-design/icons';
import { useIntl } from '@umijs/max';
import { Button, message, Modal } from 'antd';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import { useModel } from 'umi';

const { confirm } = Modal;

export type Props = {
  date: string;
};

const Index: React.FC<Props> = ({ date }) => {
  const intl = useIntl();
  const { stationId } = useModel('@@initialState')?.initialState || {};
  const [addMonthStatus, setAddMonthStatus] = useState(false);
  const [disabled, setDisabled] = useState(false);

  useEffect(() => {
    if (moment(date).isBefore(moment(), 'month')) {
      setAddMonthStatus(true);
    } else {
      checkAddMonth({ date }).then((res) => {
        //当天已添加进月度评估报告
        if (res?.code === 10207) {
          setAddMonthStatus(true);
        }
        if (res?.success) {
          setAddMonthStatus(false);
        }
      });
    }
  }, [date]);

  return (
    <Button
      className="global-main-color"
      type="text"
      disabled={addMonthStatus || disabled}
      onClick={async () => {
        setDisabled(true);
        confirm({
          title: intl.formatMessage({ id: 'global.prompt' }),
          content: intl.formatMessage({ id: 'batteryVoltage.vol.reportName' }),
          onOk: async () => {
            try {
              const res = await addMonth({ date, stationId });
              if (res.success) {
                message.success(intl.formatMessage({ id: 'global.monthReport' }));
                return true;
              }
            } catch (error) {
              message.error(intl.formatMessage({ id: 'global.addFailedTips' }));
              return false;
            }
          },
          afterClose: () => {
            setDisabled(false);
          },
        });
      }}
    >
      <PlusOutlined style={{ verticalAlign: -2 }} />
      {intl.formatMessage({ id: 'batteryVoltage.vol.reportName' })}
    </Button>
  );
};
export default Index;
